On Error Resume Next

Function IsArrayDimmed(arr)
   IsArrayDimmed = False
   If IsArray(arr) Then
     On Error Resume Next
     Dim ub : ub = UBound(arr)
     If (Err.Number = 0) And (ub >= 0) Then IsArrayDimmed = True
   End If  
 End Function

Function ExecuteWithTerminalOutput(cmd, noRun)
	Set sh = WScript.CreateObject("WScript.Shell")
	if noRun then
		WScript.Echo "%comspec% /c " + cmd
	else
		shErr = sh.Run ("%comspec% /c " + cmd ,1,true)
	end if
End Function

set args = WScript.Arguments
'
' Procitaj argumente ako su zadani
'
novaBaza = ""
dbHostname = ""
dbInstance = ""
installFolder = ""
For Each strArg in args
    if strArg = "/?" then writeHelp = 1
	if strArg = "/n" then noRun = 1
    if strArg = "/l" then writeLog = 1
    if strArg = "/c" then
        Set fso = CreateObject("Scripting.FileSystemObject") 
        installFolder = fso.GetParentFolderName(wscript.ScriptFullName)
    end if
	select case left(strArg,3) 
		case "/s:"
			dbHostname = Mid(strArg,4)
		case "/i:"
			dbInstance = Mid(strArg,4)
		case "/d:"
			novaBaza = Mid(strArg,4)
	end select
Next

if writeHelp then
    WScript.Echo "/n ne pokreci osql naredbe, samo napisi kako bi one izgledale"
    WScript.Echo "/s:IME_SQL_SERVERA server gdje ce se napravit nova baza"
    WScript.Echo "/i:INSTANCA instanca gdje se pokrecu skripte,"
    WScript.Echo "            ako se radi o neimenovanoj instanci onda upisati DEFAULT"
    WScript.Echo "/d:IME_BAZE ime nove baze"
    WScript.Echo "/l sprema log pokrenutih naredbi u log_IME_BAZE.txt"
    WScript.Echo "/c uzima skripte iz trenutnog direktorija"
    WScript.Quit -100
end if
'
' Procitaj default ime baze iz registrya
'
Set myShell = CreateObject("WScript.Shell")
dbDefaultName = myShell.RegRead("HKLM\Software\NappDb\DbDefaultName")
if dbDefaultName ="" then
	dbDefaultName = myShell.RegRead("HKLM\Software\Wow6432Node\NappDb\DbDefaultName")
end if
'
' Pitaj ime baze ako nije specificirano u argumenzima
'
if novaBaza = "" then novaBaza  = InputBox("Ime nove baze:", "Dodavanje napp baze", dbDefaultName)
'
' Provjeri da ime baze ima samo a-z, 0-9 i hrv znakove
'
set myRegEx = new RegExp
myRegEx.IgnoreCase = true
myRegEx.Pattern = "[^a-z0-9\s\u010D\u0107\u0160\u017D\u0110]"
if myRegEx.Test(novaBaza) then 
	WScript.Echo("Nedozvoljeno ime baze podataka! Ime smije sadrzavati znakove a-z, 0-9 i razmak.")
	WScript.Quit -100
end if
'
' Provjeri je li baza s tim imenom vec upisana u registry?
'
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
    strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\NappDb"
strValueName = "nappBaze"
oReg.GetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,arrValues
if Not IsArrayDimmed(arrValues) Then
	strKeyPath = "SOFTWARE\Wow6432Node\NappDb"
	oReg.GetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,arrValues
end if
For Each strValue In arrValues
    if strValue = novaBaza then 
    	regPostoji = true
    	if msgbox("Baza s tim imenom vec je upisana u registry! Zelite li svejedno nastaviti?", 4) = 7 then WScript.Quit -100
	end if
Next

'
' procitati iz registrya gdje je server i gdje je aplikacija instalirana
'
if installFolder = "" then installFolder = myShell.RegRead("HKLM\Software\NappDb\InstallationFolder")
if installFolder ="" then
	installFolder = myShell.RegRead("HKLM\Software\Wow6432Node\NappDb\InstallationFolder")
end if
if dbHostname = "" then dbHostname=myShell.RegRead("HKLM\Software\NappDb\DbHostname")
if dbHostname = "" then
	dbHostname=myShell.RegRead("HKLM\Software\Wow6432Node\NappDb\DbHostname")
end if
if dbInstance = "" then dbInstance = myShell.RegRead("HKLM\Software\NappDb\DbInstance")
if dbInstance ="" then
	dbInstance = myShell.RegRead("HKLM\Software\Wow6432Node\NappDb\DbInstance")
end If
'
' ako je DEFAULT instanca postavi prazno
'
If dbInstance = "DEFAULT" Then dbInstance = ""
'
' ako je upisana instanca, dodaj backslash ispred
'
if (not dbInstance = "") Then dbInstance = "\" + dbInstance 

'
' ako su server ili ime nove baze prazni napisi error
'
if dbHostname = "" or novaBaza = ""  then
    WScript.Echo "Server ili ime baze ne smiju biti prazni"
	WScript.Quit -100
end if


'
' Spoji se na bazu, ako je ok, provjeri postoji li vec baza s istim imenom i pokreni skripte
' Skripte procitaj iz install foldera
'
set db = CreateObject("ADODB.Connection")
db.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=" & dbHostname & dbInstance
if db.State = 0 then
	WScript.Echo("Veza sa serverom nije uspostavljena.")
	WScript.Quit -100
end if

'
' 
'
if writeLog then
    logScript = " > " + """" + "log_" + novaBaza + ".txt" + """"
    appendLogScript = " >> " + """" + "log_" + novaBaza + ".txt" + """"
end if

Dim rs
set rs = db.Execute("SELECT COUNT(NAME) FROM master.dbo.sysdatabases WHERE NAME = '" + novaBaza + "'")
' ako baza ne postoji, napravi ju i pokreni skripte
if rs(0) = 0 then
	WScript.Echo "Stvaranje baze podataka..." 
	ExecuteWithTerminalOutput "osql -n -E -S " + dbHostname + dbInstance +  " -Q """ + "CREATE DATABASE [" + novaBaza + "] COLLATE Croatian_Ci_As""" + logScript, noRun
    WScript.Echo "Podesavanje recovery modela baze podataka..." 
	ExecuteWithTerminalOutput "osql -n -E -S " + dbHostname + dbInstance +  " -Q """ + "ALTER DATABASE [" + novaBaza + "] SET RECOVERY FULL""" + appendLogScript, noRun
	WScript.Echo "Stvaranje tablica, view-ova, funkcija, procedura..." 
	ExecuteWithTerminalOutput "osql -n -E -S " + dbHostname + dbInstance + " -d """ + novaBaza + """ -i " + """" + installFolder + "\schema.sql" + """" + appendLogScript, noRun
	WScript.Echo "Upisivanje osnovnih podataka..." 
	ExecuteWithTerminalOutput "osql -n -E -S " + dbHostname + dbInstance + " -d """ + novaBaza + """ -i " + """" + installFolder + "\data.sql" + """" + appendLogScript, noRun
	WScript.Echo "Upisivanje definicija izvjestaja..." 
	ExecuteWithTerminalOutput "osql -n -E -S " + dbHostname + dbInstance + " -d """ + novaBaza + """ -i " + """" + installFolder + "\report.sql" + """" + appendLogScript, noRun
	WScript.Echo "Upisivanje izvjestaja..."
	ExecuteWithTerminalOutput "osql -n -d """ + novaBaza + """ -E -S " + dbHostname + dbInstance + " -Q """ + "BULK INSERT tblReportiServer FROM '" + installFolder +"\tblReportiServer.dat' WITH (DATAFILETYPE='native')""" + appendLogScript, noRun
	' dodaj u registry da je baza napravljena
	if (not regPostoji) and (noRun <> 1) then
		ReDim Preserve arrValues(UBound(arrValues) + 1)
		arrValues(UBound(arrValues)) = novaBaza
		oReg.SetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,arrValues
	end if
else
	WScript.Echo("Baza s tim imenom vec postoji na serveru!")
end if

Set myShell = nothing
set rs = nothing
set db = nothing
